#include "Semaphore.hpp"

#include <iostream>
#include <string>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/wait.h>
#include <cstdlib>
#include <ctime>

int main()
{
    Semaphore sem;
    sem.Creat_Sem();

    srand((unsigned)time(nullptr));

    std::cout << std::unitbuf;
    int pid = fork();
    if (pid == 0)
    {
        sem.Get_Sem();
        for (int i = 0; i < 10; i++)
        {
            sem.P();

            std::cout << "A";
            usleep(rand() % 100860);
            std::cout << "A";
            usleep(rand() % 1860);
            sem.V();
        }

        exit(0);
    }

    for (int i = 0; i < 10; i++)
    {
        sem.P();

        std::cout << "B";
        usleep(rand() % 100860);
        std::cout << "B";
        usleep(rand() % 1860);
        sem.V();
    }
    waitpid(pid , nullptr , 0);
    sem.Destory_Sem();

    return 0;
}